<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
    userPageService, userUpdateService, userByIdService, userRoleUpdateService,
    userDeleteByIdService, userAddService, userRoleService, userRoleByIdService
} from '@/api/user'
// 导入tokenstore
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore()

// 查询条件
const search = ref({})

// 数据列表
const tableData = ref([]);

// 角色列表
const roleList = ref([])

// 编辑表单数据
const dialogEditForm = ref([])

// 添加表单数据
const dialogAddForm = ref([])

// 角色分配表单数据
const dialogRoleForm = ref([])

// 多选
const selectedIds = ref([])

// 分页
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总数
const total = ref(0);

// 状态选项
const statusOptions = [
    { label: '正常', value: '正常' },
    { label: '禁用', value: '禁用' }
];

// 性别选项
const genderOptions = [
    { label: '男', value: '1' },
    { label: '女', value: '0' }
];

// 编辑表单显隐
const dialogEditVisible = ref(false)

// 角色分配表单显隐
const dialogRoleVisible = ref(false)

// 添加表单显隐
const dialogAddVisible = ref(false)

// 密码框状态管理
const passwordPlaceholder = ref('123456')
const isPasswordDefault = ref(true)

// 规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 15, message: '长度在6到15个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    'userInfo.nickName': [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ]
};

onMounted(() => {
    handleSearch()
    getRoleList()
})

// 查询
const handleSearch = async () => {
    search.value.pageSize = pageSize.value;
    console.log(search.value);
    const result = await userPageService(search.value)
    tableData.value = result.data.list
    total.value = parseInt(result.data.total)
}

// 获取角色列表
const getRoleList = async () => {
    const result = await userRoleService()
    roleList.value = result.data
    console.log(roleList.value);

}

// 清空条件
const clearSearch = () => {
    search.value = {}
    handleSearch()
}

// 获取选择列表
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
};

// 添加
const handleAdd = async () => {
    dialogAddVisible.value = true;
    dialogAddForm.value = {
        username: '',
        password: passwordPlaceholder.value,  // 使用占位符
        phone: ''
    }
    isPasswordDefault.value = true
    console.log(dialogAddForm.value);
}

// 编辑
const handleEdit = async (id) => {
    const result = await userByIdService(id);
    const data = result.data;

    // 清空
    dialogEditForm.value = {}

    // 深度拷贝用户数据
    dialogEditForm.value = {
        ...data,
        userInfo: { ...data.userInfo },
        createDate: data.createDate ? dayjs(data.createDate).format('YYYY-MM-DD') : ''
    };

    dialogEditVisible.value = true;
}

// 分配角色
const handleRole = async (id) => {
    const result = await userRoleByIdService(id);
    dialogRoleForm.value = result.data
    console.log("分配的角色", dialogRoleForm.value);
    dialogRoleVisible.value = true
}

// 保存
const saveEdit = async () => {

    try {
        if (dialogEditVisible.value) {
            // 更新用户信息
            await userUpdateService(dialogEditForm.value);
            ElMessage.success('更新成功!');
            dialogEditVisible.value = false
        } else if (dialogRoleVisible.value) {
            // 更新角色
            await userRoleUpdateService(dialogRoleForm.value);
            dialogRoleVisible.value = false
        } else {
            // 创建新用户
            console.log(dialogAddForm.value);
            await userAddService(dialogAddForm.value);
            ElMessage.success('添加成功!');
            dialogAddVisible.value = false
        }

        handleSearch();
    } catch (error) {
        ElMessage.error('操作失败：' + error.message);
    }
}

// 删除
const handleDelete = async (id) => {
    // 删除
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 确定删除
        await userDeleteByIdService(id);
        ElMessage.success('删除成功!');
        handleSearch();
    }).catch(() => {
        // 取消删除
        ElMessage.info('已取消删除');
    })
}

// 密码框聚焦处理
const handlePasswordFocus = () => {
    if (isPasswordDefault.value) {
        dialogAddForm.value.password = ''
        isPasswordDefault.value = false
    }
}

// 密码框失焦处理
const handlePasswordBlur = () => {
    if (!dialogAddForm.value.password) {
        dialogAddForm.value.password = passwordPlaceholder.value
        isPasswordDefault.value = true
    }
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
    // 同步更新 pageSize
    pageSize.value = val;
    // 同步更新搜索参数
    search.value.pageSize = val;
    console.log(`每页 ${val} 条`);
    handleSearch();
}
// 页码变化时触发
const handleCurrentChange = (val) => {
    // 同步更新 currentPage
    currentPage.value = val;
    // 同步更新搜索参数
    search.value.pageNum = val;
    console.log(`当前页: ${val}`);
    handleSearch();
}

// 文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
    dialogEditForm.value.userInfo.profilePicture = response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只支持上传图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('只能上传10M以内图片')
        return false
    }
    return true
}
</script>

<template>
    <div>
        <!-- 数据列表标题和添加按钮 -->
        <div class="card-header">
            <el-card shadow="never">
                <!-- 筛选搜索区域 -->
                <el-form :model="search" label-width="100px">
                    <el-row :gutter="15">
                        <!-- 第一行 -->
                        <el-col :span="5">
                            <el-form-item label="输入搜索：">
                                <el-input v-model="search.keyword" placeholder="账号或手机号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="处理状态：">
                                <el-select v-model="search.status" placeholder="全部" style="width: 100%">
                                    <el-option label="全部" value=""></el-option>
                                    <el-option label="正常" value="1"></el-option>
                                    <el-option label="冻结" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col style="margin: 0 0 0 37%;" :span="5">
                            <el-button type="info" @click="clearSearch">清空</el-button>
                            <el-button type="primary" @click="handleSearch">查询</el-button>
                            <el-button type="success" @click="handleAdd">添加</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" class="table-list">
            <el-table-column align="center" label="编号" prop="id" width="120"></el-table-column>
            <el-table-column align="center" label="账号" prop="username" width="250"></el-table-column>
            <el-table-column align="center" label="手机号" prop="phone" width="250"></el-table-column>
            <el-table-column align="center" label="添加日期" prop="createDate" width="200"></el-table-column>
            <el-table-column align="center" label="最后登录时间" prop="userLoginLog.createTime" width="200"></el-table-column>
            <el-table-column align="center" label="状态" width="120">
                <template #default="scope">
                    <!-- 使用状态映射规范 -->
                    <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template align="center" #default="scope">
                    <el-button type="primary" text @click="handleRole(scope.row.id)">分配角色</el-button>
                    <el-button type="primary" text @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button type="danger" text @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20, 30, 50, 100]" size="default" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
    <!-- 分配角色表单 -->
    <el-dialog v-model="dialogRoleVisible" title="分配角色" width="30%">
        <el-form :model="dialogRoleForm" label-width="120px" label-position="right" :rules="rules" ref="formRef">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item style="width: 300px;" label="角色：" prop="id">
                        <el-select v-model="dialogRoleForm.roleId" placeholder="请选择">
                            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogRoleVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑表单 -->
    <el-dialog v-model="dialogEditVisible" title="编辑用户" width="50%">
        <el-form :model="dialogEditForm" label-width="120px" label-position="right" :rules="rules" ref="formRef">
            <!-- 用户基本信息 -->
            <!-- 头像上传 -->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-form-item label="头像：" prop="userInfo.profilePicture">
                        <span class="el-icon-upload">
                            <el-upload class="avatar-uploader" action="/api/users/upload" name="file" :headers="{
                                Authorization: tokenStore.token,
                            }" :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="dialogEditForm.userInfo.profilePicture"
                                    :src="dialogEditForm.userInfo.profilePicture" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <img src="/src/assets/images/default.png" alt="">
                                </el-icon>
                            </el-upload>
                        </span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="用户名：" prop="username">
                        <el-input v-model="dialogEditForm.username" />
                    </el-form-item>
                    <el-form-item label="手机号：" prop="phone">
                        <el-input v-model="dialogEditForm.phone" />
                    </el-form-item>
                    <el-form-item label="状态：" prop="status">
                        <el-select v-model="dialogEditForm.status" placeholder="请选择">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="余额：">
                        <!-- TODO: 添加余额可更改判定 -->
                        <el-input v-model="dialogEditForm.userInfo.balance" :precision="2" :step="100" style="width: 100%"
                            readony />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 用户详细信息 -->
            <el-divider content-position="left">详细信息</el-divider>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="昵称：" prop="userInfo.nickName">
                        <el-input v-model="dialogEditForm.userInfo.nickName" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别：">
                        <el-select v-model="dialogEditForm.userInfo.gender" placeholder="请选择">
                            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="生日：" prop="userInfo.birthday">
                        <el-date-picker v-model="dialogEditForm.userInfo.birthday" type="date" placeholder="选择日期"
                            style="width: 100%" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="年龄：" prop="userInfo.age">
                        <el-input-number v-model="dialogEditForm.userInfo.age" :min="0" :max="150"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="邮箱：" prop="userInfo.email">
                        <el-input v-model="dialogEditForm.userInfo.email" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="简介：" prop="userInfo.introduction">
                        <el-input v-model="dialogEditForm.userInfo.introduction" type="textarea" :rows="3"
                            show-word-limit maxlength="200" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 地址信息 -->
            <el-divider content-position="left">地址信息</el-divider>
            <div v-if="dialogEditForm.addressList.length === 0" style="text-align: center; color: #999;">暂无地址信息</div>
            <el-table :data="dialogEditForm.addressList" v-else style="width: 100%">
                <el-table-column prop="contact" label="联系人" />
                <el-table-column prop="mobile" label="手机号" />
                <el-table-column prop="province" label="省" />
                <el-table-column prop="city" label="市" />
                <el-table-column prop="town" label="镇/县" />
                <el-table-column prop="street" label="详细地址" />
            </el-table>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 添加表单 -->
    <el-dialog v-model="dialogAddVisible" title="添加用户" width="30%">
        <el-form :model="dialogAddForm" label-width="100" label-position="right" :rules="rules" ref="formRef">
            <el-form-item label="用户名：" prop="username">
                <el-input v-model="dialogAddForm.username" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
                <el-input v-model="dialogAddForm.password" @focus="handlePasswordFocus" @blur="handlePasswordBlur"/>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <el-input v-model="dialogAddForm.phone" />
                </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
/* card 样式 */
.card-header {
    width: 96%;
    margin: 0 0 0 2%;
}

/* card标题栏样式 */
.card-title {
    margin-right: 80%;
}

/* 表格样式 */
.table-list {
    width: 96%;
    margin: 3vh 0 3vh 2%;

}

.el-pagination {
    margin: 0 0 0 25% !important;
}

.el-icon-upload {
    margin: 20% 0 0 20%;
}

/* 头像上传样式 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 50%;
}

/* 表单布局优化 */
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

/* 分割线样式 */
.el-divider__text {
    font-weight: bold;
    font-size: 14px;
}

.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>